import sysConfig from '@/config/index'
import tool from '@/utils/tool'
import * as signalR from '@microsoft/signalr'
import * as message from './message'
//使用signalr
export default function useSignalr() {
	const userInfo = tool.data.get('USER_INFO') //用户信息
	let socketUrl = sysConfig.API_URL + '/hubs/simple' //socket地址

	//开始
	const startSignalr = () => {
		//初始化连接
		const connection = init()
		// 启动连接
		connection.start().then(() => {
			console.log('连接成功')
		})
	}

	//初始化
	const init = () => {
		// SignalR对象
		const connection = new signalR.HubConnectionBuilder()
			.withUrl(socketUrl, {
				accessTokenFactory: () => tool.data.get(sysConfig.ACCESS_TOEKN_KEY)
			})
			.withAutomaticReconnect({
				nextRetryDelayInMilliseconds: () => {
					return 5000 // 每5秒重连一次
				}
			}) //自动重新连接
			.configureLogging(signalR.LogLevel.Warning)
			.build()
		connection.keepAliveIntervalInMilliseconds = 15 * 1000 // 心跳检测15s

		// 断开连接
		connection.onclose(async () => {
			console.log('断开连接')
		})

		//断线重新
		connection.onreconnected(() => {
			console.log('断线重新连接成功')
		})
		//消息处理
		receiveMsg(connection)
		return connection
	}

	//接收消息处理
	const receiveMsg = (connection) => {
		// 登出
		connection.on('LoginOut', (data) => {
			message.loginOut(data)
		})

		// 新消息
		connection.on('NewMessage', (data) => {
			message.NewMessage(data)
		})

		// 修改密码
		connection.on('UpdatePassword', (data) => {
			message.SystemNotice(data)
		})
	}

	//页面销毁
	onUnmounted(() => {})
	return { startSignalr }
}
